<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>发布需求</title>
    
    <!-- Favicon -->
    <link rel="icon" type="image/x-icon" href="../favicon.ico">
    <link rel="icon" type="image/png" href="../images/logo.png">
    
    <script src="../js/tailwindcss-3.4.17.js"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#10b981',
                        'primary-dark': '#059669',
                        secondary: '#3b82f6',
                        accent: '#f59e0b',
                        danger: '#ef4444',
                        neutral: '#f9fafb',
                        'text-primary': '#1f2937',
                        'text-secondary': '#6b7280'
                    }
                }
            }
        }
    </script>
    <link rel="stylesheet" href="../css/all.min.css">
    <link rel="stylesheet" href="../css/common.css">
</head>
<body class="bg-neutral">
    <div class="container-app">
        <!-- 顶部导航栏 -->
        <header class="bg-white sticky top-0 z-10 border-b border-gray-100 shadow-soft">
            <div class="px-4 py-3 flex items-center gap-3">
                <button onclick="window.history.back()" class="w-8 h-8 rounded-lg hover:bg-gray-100 flex items-center justify-center transition-colors">
                    <i class="fa fa-arrow-left text-text-primary"></i>
                </button>
                <h1 class="text-base font-bold flex-1 text-text-primary">发布需求</h1>
                <button onclick="saveDraft()" class="text-xs text-primary hover:underline">保存草稿</button>
            </div>
        </header>
        
        <!-- 表单内容 -->
        <main class="px-4 py-4 pb-24">
            <form id="publish-demand-form" class="space-y-3">
                <!-- 需求名称 -->
                <div class="card-modern p-3">
                    <label class="block text-sm font-bold text-text-primary mb-2">
                        需求名称 <span class="text-danger">*</span>
                    </label>
                    <input type="text" name="demandName" required
                           placeholder="请输入需求名称，如：寻找大型收割机服务"
                           class="w-full px-3 py-2.5 bg-neutral rounded-lg text-sm border border-gray-200 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary transition-all">
                </div>

                <!-- 需求分类 -->
                <div class="card-modern p-3">
                    <label class="block text-sm font-bold text-text-primary mb-2">
                        需求分类 <span class="text-danger">*</span>
                    </label>
                    <select name="demandCategory" id="demandCategory" required
                            class="w-full px-3 py-2.5 bg-neutral rounded-lg text-sm border border-gray-200 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary transition-all">
                        <option value="">请选择需求分类</option>
                        <!-- 选项将通过JavaScript动态加载 -->
                    </select>
                </div>

                <!-- 需求介绍（一句话） -->
                <div class="card-modern p-3">
                    <label class="block text-sm font-bold text-text-primary mb-2">
                        需求介绍 <span class="text-danger">*</span>
                    </label>
                    <input type="text" name="demandIntro" required maxlength="50"
                           placeholder="请用一句话介绍您的需求（50字以内）"
                           class="w-full px-3 py-2.5 bg-neutral rounded-lg text-sm border border-gray-200 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary transition-all">
                    <p class="text-xs text-text-secondary mt-1">这将显示在需求列表中，请简洁明了</p>
                </div>

                <!-- 需求内容（详细描述） -->
                <div class="card-modern p-3">
                    <label class="block text-sm font-bold text-text-primary mb-2">
                        需求内容 <span class="text-danger">*</span>
                    </label>
                    <textarea name="demandContent" required rows="5"
                              placeholder="请详细描述您的需求，包括具体要求、时间节点、期望标准等"
                              class="w-full px-3 py-2.5 bg-neutral rounded-lg text-sm border border-gray-200 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary transition-all resize-none"></textarea>
                    <p class="text-xs text-text-secondary mt-1">详细的需求说明有助于获得更准确的服务匹配</p>
                </div>

                <!-- 预算范围 -->
                <div class="card-modern p-3">
                    <label class="block text-sm font-bold text-text-primary mb-2">
                        预算设置 <span class="text-danger">*</span>
                    </label>
                    
                    <!-- 预算面议选择 -->
                    <div class="mb-2">
                        <div class="flex gap-2">
                            <label class="flex-1 flex items-center justify-center px-3 py-2 border-2 border-gray-200 rounded-lg cursor-pointer hover:border-primary transition-all">
                                <input type="radio" name="budgetNegotiable" value="0" checked class="mr-2" onchange="toggleBudgetInputs()">
                                <span class="text-xs font-medium">填写预算</span>
                            </label>
                            <label class="flex-1 flex items-center justify-center px-3 py-2 border-2 border-gray-200 rounded-lg cursor-pointer hover:border-primary transition-all">
                                <input type="radio" name="budgetNegotiable" value="1" class="mr-2" onchange="toggleBudgetInputs()">
                                <span class="text-xs font-medium">面议</span>
                            </label>
                        </div>
                    </div>
                    
                    <!-- 预算输入框 -->
                    <div id="budgetInputs" class="grid grid-cols-2 gap-2">
                        <input type="number" name="budgetMin" id="budgetMin" placeholder="最低预算" min="0"
                               class="px-3 py-2.5 bg-neutral rounded-lg text-sm border border-gray-200 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary transition-all">
                        <input type="number" name="budgetMax" id="budgetMax" placeholder="最高预算" min="0"
                               class="px-3 py-2.5 bg-neutral rounded-lg text-sm border border-gray-200 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary transition-all">
                    </div>
                </div>

                <!-- 需求地区 -->
                <div class="card-modern p-3">
                    <label class="block text-sm font-bold text-text-primary mb-2">
                        需求地区 <span class="text-danger">*</span>
                    </label>
                    <input type="text" name="demandLocation" required
                           placeholder="如：浙江杭州、江苏全省"
                           class="w-full px-3 py-2.5 bg-neutral rounded-lg text-sm border border-gray-200 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary transition-all">
                </div>

                <!-- 需求时效 -->
                <div class="card-modern p-3">
                    <label class="block text-sm font-bold text-text-primary mb-2">
                        需求时效
                    </label>
                    <select name="demandUrgency" id="demandUrgency"
                            class="w-full px-3 py-2.5 bg-neutral rounded-lg text-sm border border-gray-200 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary transition-all">
                        <!-- 选项将通过JavaScript动态加载 -->
                    </select>
                </div>

                <!-- 联系人信息 -->
                <div class="card-modern p-3">
                    <h3 class="text-sm font-bold text-text-primary mb-2 flex items-center">
                        <i class="fa fa-user-circle text-primary mr-2"></i>
                        联系人信息
                    </h3>
                    
                    <div class="space-y-2">
                        <div>
                            <label class="block text-xs text-text-secondary mb-1">
                                联系人 <span class="text-danger">*</span>
                            </label>
                            <input type="text" name="contactName" required
                                   placeholder="请输入真实姓名"
                                   class="w-full px-3 py-2.5 bg-neutral rounded-lg text-sm border border-gray-200 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary transition-all">
                        </div>
                        
                        <div>
                            <label class="block text-xs text-text-secondary mb-1">
                                联系电话 <span class="text-danger">*</span>
                            </label>
                            <input type="tel" name="contactPhone" required pattern="[0-9]{11}"
                                   placeholder="请输入11位手机号"
                                   class="w-full px-3 py-2.5 bg-neutral rounded-lg text-sm border border-gray-200 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary transition-all">
                            <p class="text-xs text-text-secondary mt-1">
                                <i class="fa fa-shield mr-1"></i>
                                您的联系方式将脱敏显示
                            </p>
                        </div>
                    </div>
                </div>

                <!-- 需求协议 -->
                <div class="card-modern p-3">
                    <label class="flex items-start gap-2">
                        <input type="checkbox" name="agreement" required class="mt-0.5 w-4 h-4 text-primary rounded">
                        <span class="text-xs text-text-secondary flex-1">
                            我已阅读并同意 <a href="#" class="text-primary hover:underline">《需求发布协议》</a> 和 <a href="#" class="text-primary hover:underline">《平台使用规范》</a>，承诺发布的信息真实有效
                        </span>
                    </label>
                </div>
            </form>
        </main>
        
        <!-- 底部操作按钮 -->
        <div class="fixed bottom-0 left-0 right-0 max-w-md mx-auto bg-white border-t border-gray-200 p-4 shadow-xl z-20">
            <div class="text-center mb-3">
                <p class="text-xs text-text-secondary">
                    <i class="fa fa-info-circle mr-1"></i>
                    提交后需等待平台审核，您可在<span class="text-primary font-medium">「我的需求」</span>中查看审核状态
                </p>
            </div>
            <div class="flex gap-3">
                <button type="button" onclick="previewDemand()" 
                        class="flex-1 py-3 bg-gray-100 text-text-primary rounded-xl font-medium hover:bg-gray-200 transition-colors">
                    预览
                </button>
                <button type="submit" form="publish-demand-form" id="submit-btn"
                        class="flex-1 py-3 bg-primary hover:bg-primary-dark text-white rounded-xl font-medium transition-colors shadow-medium">
                    发布需求
                </button>
            </div>
        </div>
    </div>
    
    <script src="../js/common.js"></script>
    <script src="../js/animate.js"></script>
    <script>
        // 初始化Token和字典数据
        document.addEventListener('DOMContentLoaded', async function() {
            CommonUtils.initToken();
            
            // 检查商户权限
            const hasPermission = await CommonUtils.checkMerchantRequired(null, '发布需求');
            if (!hasPermission) {
                // 如果没有权限，延迟返回前一页
                setTimeout(() => {
                    window.history.back();
                }, 2000);
                return;
            }
            
            // 加载需求分类字典
            await loadDictData('xqfl', 'demandCategory');
            
            // 加载需求时效字典
            await loadDictData('xqsx', 'demandUrgency');
            
            // 字典加载完成后，恢复草稿
            restoreDraft();
        });
        
        // 加载字典数据
        async function loadDictData(dictType, selectId) {
            try {
                const result = await CommonUtils.getDictDataByTypeAPI(dictType);
                
                if (result.code === 200 && result.data) {
                    const selectElement = document.getElementById(selectId);
                    
                    // 清空现有选项（保留第一个"请选择"选项）
                    while (selectElement.options.length > 1) {
                        selectElement.remove(1);
                    }
                    
                    // 添加字典选项
                    result.data.forEach((item, index) => {
                        const option = document.createElement('option');
                        option.value = item.dictValue;  // 使用dictValue作为值
                        option.textContent = item.dictLabel;
                        
                        // 如果是需求时效，默认选中"普通"（假设dictValue为2）
                        if (selectId === 'demandUrgency' && item.dictValue === '2') {
                            option.selected = true;
                        }
                        
                        selectElement.appendChild(option);
                    });
                }
            } catch (error) {
                console.error(`加载${dictType}字典失败:`, error);
                CommonUtils.showToast(`加载字典数据失败`, 'error');
            }
        }
        
        // 切换预算输入框显示/隐藏
        function toggleBudgetInputs() {
            const budgetNegotiable = document.querySelector('input[name="budgetNegotiable"]:checked').value;
            const budgetInputs = document.getElementById('budgetInputs');
            const budgetMinInput = document.getElementById('budgetMin');
            const budgetMaxInput = document.getElementById('budgetMax');
            const labels = document.querySelectorAll('input[name="budgetNegotiable"]').forEach(radio => {
                radio.parentElement.classList.remove('border-primary', 'bg-primary/5');
                if (radio.checked) {
                    radio.parentElement.classList.add('border-primary', 'bg-primary/5');
                }
            });
            
            if (budgetNegotiable === '1') {
                // 选择面议：隐藏输入框并清空值
                budgetInputs.style.display = 'none';
                budgetMinInput.value = '';
                budgetMaxInput.value = '';
            } else {
                // 选择填写预算：显示输入框
                budgetInputs.style.display = 'grid';
            }
        }
        
        // 表单提交处理
        document.getElementById('publish-demand-form').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            // 验证表单
            const formData = new FormData(this);
            
            // 检查是否同意协议
            if (!formData.get('agreement')) {
                CommonUtils.showToast('请先阅读并同意需求发布协议', 'warning');
                return;
            }
            
            // 检查登录状态
            if (!CommonUtils.isLoggedIn()) {
                CommonUtils.showToast('请先登录', 'warning');
                setTimeout(() => {
                    window.location.href = './login.html';
                }, 1500);
                return;
            }
            
            // 获取表单数据
            const budgetNegotiable = parseInt(formData.get('budgetNegotiable'));
            const demandData = {
                demandName: formData.get('demandName'),
                demandCategory: formData.get('demandCategory'),
                demandIntro: formData.get('demandIntro'),
                demandContent: formData.get('demandContent'),
                budgetMin: budgetNegotiable === 0 && formData.get('budgetMin') ? parseFloat(formData.get('budgetMin')) : null,
                budgetMax: budgetNegotiable === 0 && formData.get('budgetMax') ? parseFloat(formData.get('budgetMax')) : null,
                budgetNegotiable: budgetNegotiable,
                demandLocation: formData.get('demandLocation'),
                demandUrgency: formData.get('demandUrgency'),
                contactName: formData.get('contactName'),
                contactPhone: formData.get('contactPhone'),
                urgency: formData.get('urgency')
            };
            
            // 提交按钮状态
            const submitBtn = document.getElementById('submit-btn');
            if (submitBtn) {
                submitBtn.disabled = true;
                submitBtn.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i>发布中...';
            }
            
            try {
                // 调用API
                const result = await CommonUtils.publishDemandAPI(demandData);
                
                if (result.code === 200) {
                    // 清除草稿
                    localStorage.removeItem('demand-draft');
                    
                    // 显示成功通知并提示跳转
                    CommonUtils.showToast('需求提交成功！正在跳转到我的需求列表...', 'success');
                    
                    // 延迟跳转到个人中心-我的需求
                    setTimeout(() => {
                        window.location.href = './my-posts.html';
                    }, 1500);
                } else {
                    throw new Error(result.msg || '发布失败');
                }
            } catch (error) {
                console.error('发布需求失败:', error);
                CommonUtils.showToast(error.message || '发布失败，请稍后重试', 'error');
                
                // 恢复提交按钮
                if (submitBtn) {
                    submitBtn.disabled = false;
                    submitBtn.innerHTML = '发布需求';
                }
            }
        });
        
        // 保存草稿
        function saveDraft() {
            const formData = new FormData(document.getElementById('publish-demand-form'));
            localStorage.setItem('demand-draft', JSON.stringify(Object.fromEntries(formData)));
            CommonUtils.showToast('草稿已保存', 'success');
        }
        
        // 预览需求
        function previewDemand() {
            const formData = new FormData(document.getElementById('publish-demand-form'));
            
            if (!formData.get('demandName')) {
                CommonUtils.showToast('请先填写需求名称', 'warning');
                return;
            }
            
            // 保存到 sessionStorage 用于预览
            sessionStorage.setItem('preview-demand', JSON.stringify(Object.fromEntries(formData)));
            window.open('demand-detail.html?preview=1', '_blank');
        }
        
        // 恢复草稿（在字典加载完成后调用）
        function restoreDraft() {
            const draft = localStorage.getItem('demand-draft');
            if (draft) {
                const confirmed = confirm('检测到未完成的草稿，是否恢复？');
                if (confirmed) {
                    const data = JSON.parse(draft);
                    const form = document.getElementById('publish-demand-form');
                    Object.keys(data).forEach(key => {
                        if (key === 'budgetNegotiable') {
                            // 恢复单选框状态
                            const radio = form.querySelector(`input[name="${key}"][value="${data[key]}"]`);
                            if (radio) {
                                radio.checked = true;
                                toggleBudgetInputs(); // 触发显示/隐藏逻辑
                            }
                        } else {
                            const input = form.querySelector(`[name="${key}"]`);
                            if (input) {
                                if (input.type === 'checkbox') {
                                    input.checked = data[key] === 'on';
                                } else if (input.type === 'radio') {
                                    if (input.value === data[key]) {
                                        input.checked = true;
                                    }
                                } else {
                                    input.value = data[key];
                                }
                            }
                        }
                    });
                } else {
                    // 如果用户选择不恢复，删除草稿
                    localStorage.removeItem('demand-draft');
                }
            }
        }
    </script>
</body>
</html>

